'use strict';
import React, {
    Component
} from 'react'
import {
    Tips,
    getLocalTime,
    sxtUrl,
    taskFinish,
    sxtPageUrl,
    randomStr,
    iosfocus,
    iosblur
} from '../Tools'
import {
    Link,
    hashHistory
} from 'react-router'
import Header from './Common/Header'
import ConfirmBox from './Common/ConfirmBox'
import LoadingBox from './Common/LoadingBox'
import WxServer from '../Tools/WxServer';

import imgPk from '../Img/mall/pk2.png'
import imgPackage from '../Img/mall/package1.png'
import imgHead from '../Img/other/parent_default.png'

import imgDetail from '../Img/info/detail.png'
import imgPengyou from '../Img/info/pengyou.png'
import imgSharedirect from '../Img/info/sharedirect.png'
import imgWeixin from '../Img/info/weixin.png'
import imgWeb from '../Img/info/web.png'
import imgQQ from '../Img/info/qq.png'
import imgQQZone from '../Img/info/qqzone.png'

export default class InfoDetail extends Component {
    constructor(props) {
        super(props)
        this.state = {
            data: {},
            dataLoad: 1,
            dataEnd: 0,
            dataNull: 0,
            dataList: [],
            integralList: [],
            comment: 0,
            sigle: 0,
            sharetips: 0,
            banner: this.props.params.sign == 'banner'
        }
        this.page = 1;
        this.pagesize = 10;
        this.toBottom = 60;
        this.articleId = ''
        this.data = {
            title: '资讯详情',
            describe: '',
            url: `${location.href.split('#')[0]}#/InfoDetail/${this.props.params.id}/share${this.props.params.sign == 'banner' ? '/banner' : ''}`,
            imgUrl: `${location.href.split('#')[0]}dist/logo_bg.png`
        }
        this.replayShow = true;
        this.config = {
            content: '领取优惠券成功',
            cancelName: '确定',
            sureName: '查看详情'
        }
        this.banner = this.state.banner
    }
    componentWillMount() {

        if (/micromessenger/.test(navigator.userAgent.toLowerCase())) {
            if (sessionStorage.wxinit != 1)
                WxServer.init()
        }
        this.getDetail()
        window.shareStatus = function(fnName) {
            // if (fnName) {
            //     Tips('分享成功')
            // }
        }
        localStorage.commentName = sessionStorage.userphone || '';
        if (!localStorage.commentName) {
            localStorage.commentName = '游客' + randomStr()
        }
    }

    componentDidMount() {
        this.replayShow = false;
        //APP底部处理
        if (this.props.params.wherefrom == 'app') {
            if (sessionStorage.wherefrom == 'ios') {
                if (window.webkit)
                    webkit.messageHandlers.bottomBar.postMessage(0);
            } else {
                if (window.appweb && window.appweb.bottomBar)
                    appweb.bottomBar(0)
            }
        }

        //加载更多
        window.onscroll = () => {
            const {
                dataEnd,
                dataNull,
                page
            } = this.state;
            if (this.dataLoad == 1 || dataEnd == 1 || dataNull == 1)
                return;
            var scrollTop = 0;
            if (document.documentElement && document.documentElement.scrollTop) {
                scrollTop = document.documentElement.scrollTop;
            } else if (document.body) {
                scrollTop = document.body.scrollTop;
            }

            if (document.body.clientHeight - window.innerHeight - scrollTop <= this.toBottom) {
                this.page++;
                this.getData();
            }
        }
    }

    componentWillReceiveProps() {
        console.log('componentWillReceiveProps');
        this.articleId = location.hash.split('/')[2]
        this.banner = location.hash.indexOf('banner') > -1 ? true : false
        this.setState({
            banner: this.banner
        })
        this.getDetail(this.articleId);
        if (document.documentElement && document.documentElement.scrollTop) {
            document.documentElement.scrollTop = 0;
        } else if (document.body) {
            document.body.scrollTop = 0;
        }
        //location.reload();
    }

    //微信初始化
    weixinShareInit() {
        if (/micromessenger/.test(navigator.userAgent.toLowerCase())) {
            const title = this.data.title,
                desc = this.data.describe,
                link = this.data.url,
                imgUrl = this.data.imgUrl;
            let rct = this;
            wx.onMenuShareAppMessage({
                title,
                desc,
                link,
                imgUrl,
                success: function() {
                    rct.shareSuccess(1)
                }
            });
            wx.onMenuShareTimeline({
                title,
                desc,
                link,
                imgUrl,
                success: function() {
                    rct.shareSuccess(2)
                }
            });
            wx.onMenuShareQQ({
                title,
                desc,
                link,
                imgUrl,
                success: function() {
                    rct.shareSuccess(3)
                }
            });
            wx.onMenuShareQZone({
                title,
                desc,
                link,
                imgUrl,
                success: function() {
                    rct.shareSuccess(4)
                }
            });

            wx.onMenuShareWeibo({
                title,
                desc,
                link,
                imgUrl,
                success: function() {
                    rct.shareSuccess(5)
                }
            });
        }
    }
    //分享成功
    shareSuccess(type) {
        let msg = ['朋友', '朋友圈', 'QQ', 'QQ空间', '腾讯微博'][type - 1]
        _hmt.push(['_trackEvent', 'page', 'InfoDetail2', '资讯分享-' + msg]);
        taskFinish('分享资讯', (status, config) => {
            if (status) {
                this.config = config;
                this.setState({
                    show: 1,
                    sigle: 1
                })
            }
        })
    }
    //分享
    share() {
        _hmt.push(['_trackEvent', 'page', 'InfoDetail', '资讯分享-系统']);
        if (sessionStorage.wherefrom == 'ios') {
            window.webkit.messageHandlers.shareLink.postMessage(this.data);
        } else if (sessionStorage.wherefrom == 'android') {
            appweb.shareLink(JSON.stringify(this.data))
        } else {
            this.setState({
                sharetips: 1
            })
        }
    }
    //分享:微信
    shareWeixin() {
        _hmt.push(['_trackEvent', 'page', 'InfoDetail', '资讯分享-微信']);
        if (sessionStorage.wherefrom == 'ios') {
            window.webkit.messageHandlers.shareWeixin.postMessage(this.data);
        } else {
            appweb.shareWeixin(JSON.stringify(this.data))
        }
    }
    //分享:微信朋友圈
    shareQZone() {
        _hmt.push(['_trackEvent', 'page', 'InfoDetail', '资讯分享-朋友圈']);
        if (sessionStorage.wherefrom == 'ios') {
            window.webkit.messageHandlers.shareQZone.postMessage(this.data);
        } else {
            appweb.shareQZone(JSON.stringify(this.data))
        }
    }
    //分享:微博
    shareWeibo() {
        _hmt.push(['_trackEvent', 'page', 'InfoDetail', '资讯分享-微博']);
        if (sessionStorage.wherefrom == 'ios') {
            window.webkit.messageHandlers.shareWeibo.postMessage(this.data);
        } else {
            appweb.shareWeibo(JSON.stringify(this.data))
        }
    }
    //分享:QQ
    shareQQ() {
        _hmt.push(['_trackEvent', 'page', 'InfoDetail', '资讯分享-QQ']);
        if (sessionStorage.wherefrom == 'ios') {
            window.webkit.messageHandlers.shareQQ.postMessage(this.data);
        } else {
            appweb.shareQQ(JSON.stringify(this.data))
        }
    }
    //分享:QQ空间
    shareQQZone() {
        _hmt.push(['_trackEvent', 'page', 'InfoDetail', '资讯分享-QQ空间']);
        if (sessionStorage.wherefrom == 'ios') {
            window.webkit.messageHandlers.shareQQZone.postMessage(this.data);
        } else {
            appweb.shareQQZone(JSON.stringify(this.data))
        }
    }

    //分享提示关闭
    shareTipsClose() {
        this.setState({
            sharetips: 0
        })
    }

    //点赞
    loveInfo(e) {
        let obj = e.currentTarget
        let rct = this
        if (obj.className == 'status') {
            $.ajax({
                url: sxtUrl + '/article/zanArticle',
                cache: false,
                data: `token=${sessionStorage.appToken}&articleId=${this.props.params.id}`,
                success: function(res) {
                    if (res.code == 50006) {
                        obj.className = 'status active'
                        Tips('点赞成功')
                        rct.getDetail();
                    } else {
                        Tips(res.msg)
                    }
                }
            })
        }
    }



    //评论消息
    commentMsg(type, e) {
        let id = this.props.params.id
        let content = this.refs.comment.value.replace(/\s/g, '');
        let tipName = '评论'
        if (this.articleId)
            id = this.articleId
        if (type == 2)
            content = this.refs.talk.value.replace(/\s/g, '');

        if (content.length == 0) {
            Tips('请输入评论信息')
            return;
        }
        if (!/^[\s+`~!@#$%^&*()\-=_+[\]{};'\\:"|,.<>/?？·！￥…（）—【】；‘’、“”：，。《》、a-zA-Z0-9\u4E00-\u9FA5]+$/ig.test(content)) {
            Tips('提交内容有特殊字符')
            return
        }
        if (!localStorage.commentName)
            localStorage.commentName = '游客' + randomStr()
        let data = `content=${content}&userName=${localStorage.commentName}&`
        if (type == 2) {
            tipName = '回复'
            data += `commentId=${this.commentId}`
        } else {
            data += `articleId=${id}`
        }
        let rct = this;
        $.ajax({
            url: sxtUrl + '/article/commentArticle',
            data: data,
            async: false,
            cache: false,
            success: function(res) {
                Tips(res.msg)
                if (res.code == 50006) {
                    rct.refs.comment.value = ''
                    rct.getData(2)
                    rct.setState({
                        comment: 0
                    })
                    Tips(tipName + '成功')
                }
            }
        })
    }

    //获取详情
    getDetail(id = this.props.params.id) {
        let rct = this;
        let url = sxtUrl + '/article/getArticle'
        let data = `articleId=${id}`

        if (this.banner) {
            url = sxtUrl + '/banner/getBanner'
            data = `bannerId=${id}`
        }
        if (sessionStorage.appToken && sessionStorage.appToken != '')
            data += `&token=${sessionStorage.appToken}`
        $.ajax({
            url: url,
            cache: false,
            data: data,
            success: function(res) {
                if (res.code == 50006 || (rct.banner && res.code == 10140)) {
                    rct.data.title = res.data.theme ? res.data.theme : res.data.title
                    rct.data.imgUrl = res.data.bannerUrl || res.data.litimg
                    rct.setState({
                        data: res.data,
                        dataLoad: 0
                    });
                    rct.getData(1)
                    rct.getIntegral(id)
                } else {
                    rct.setState({
                        dataLoad: 0
                    });
                    $('.detail').text('该文章不存在或已被删除')
                }
                setTimeout(() => {
                    document.getElementById('loadwx').style.display = 'none'
                    rct.data.describe = document.querySelector('.detail').innerText.replace(/\s/ig, '').substr(0, 60);
                    if (rct.data.describe == '')
                        rct.data.describe = rct.data.title
                    rct.weixinShareInit();
                }, 400)
            }
        })
    }

    //获取评论列表
    getData(status) {
        if (this.banner)
            return
        this.dataLoad = 1
        this.setState({
            dataLoad: 1,
            dataEnd: 0,
            dataNull: 0
        });
        if (status == 1)
            this.page = 1
        let id = this.props.params.id
        if (this.articleId)
            id = this.articleId
        let data = `articleId=${id}&page=${this.page}&size=${this.pagesize}`
        if (status == 2) {
            data = `articleId=${id}&page=1&size=${this.pagesize*this.page}`
        }
        let rct = this;
        $.ajax({
            url: sxtUrl + '/article/getCommentArticlePage',
            data: data,
            cache: false,
            success: function(res) {
                rct.dataLoad = 0
                rct.setState({
                    dataLoad: 0
                });
                if (res.code == 50006) {
                    //获取数据成功
                    let dataList = res.data.list
                    if (status != 1 && status != 2)
                        dataList = rct.state.dataList.concat(res.data.list);
                    rct.setState({
                        dataList
                    });
                    if (res.data.total == rct.pagesize) {
                        rct.setState({
                            dataEnd: 1
                        });
                    } else if (res.data.list.length < rct.pagesize) {
                        rct.setState({
                            dataEnd: 1
                        });
                    }
                    return;
                }
                Tips(res.msg);
            }
        })
    }

    //苹果手机样式问题
    replyContentFocus() {
        iosfocus()
    }
    replyContentBlur() {
        iosblur()
    }

    //评论处理
    commentView(type, commentId, userName, e) {
        var objTxt = document.getElementById('cmtxt');
        if (type == 0) {
            objTxt.blur();
            objTxt.value = '';
        } else {
            objTxt.setAttribute('placeholder', '回复：' + userName);
            objTxt.value = ''
            objTxt.focus();
        }
        this.commentId = commentId
        this.setState({
            comment: type
        });
    }

    //获取优惠券
    getIntegral(articleId) {
        if (!sessionStorage.appToken)
            return
        let rct = this;
        let data = `token=${sessionStorage.appToken}&schoolName=${sessionStorage.orgname}&articleId=${this.props.params.id}`;
        if (sessionStorage.userrole == '家长')
            data += `&babyId=${sessionStorage.babyid}`
        $.ajax({
            url: sxtUrl + '/article/getGoods',
            cache: false,
            data: data,
            success: function(res) {
                if (res.code == 50006) {
                    rct.setState({
                        integralList: res.data
                    });
                    // return;
                }
                // Tips(res.msg);
            }
        })
    }

    //领取优惠券
    getPackage(id, e) {
        if (e.currentTarget.className == 'checked')
            return;
        let articleId = this.props.params.id
        if (this.articleId)
            articleId = this.articleId
        let rct = this
        if (sessionStorage.appToken) {
            const data = `token=${sessionStorage.appToken}&babyId=${sessionStorage.babyid}&goodsArchivesId=${id}&articleId=${articleId}`
            $.ajax({
                url: sxtUrl + '/article/receiveGoods',
                cache: false,
                data: data,
                success: function(res) {
                    if (res.code == 50006) {
                        $(e.currentTarget).addClass('checked')
                        rct.setState({
                            show: 1,
                            sigle: 0
                        })
                        return;
                    }
                    Tips(res.data)
                }
            })
        }
    }

    /**
     * 关闭confirmBox
     */
    cfmCancel(type) {
        this.setState({
            show: 0
        });
        if (type == 1)
            location.href = `${sxtPageUrl}/integral.html#/mypackage?${localStorage.jxtUrlData}`
    }

    //查看详情
    /**
     * 确定
     * @returns {XML}
     */

    render() {
        const {
            data,
            dataLoad,
            dataEnd,
            dataNull,
            dataList,
            integralList,
            sharetips,
            show,
            banner,
            sigle,
            comment
        } = this.state;
        const {
            wherefrom,
            isShare
        } = this.props.params
        let dataLists = dataList.map((item) => {
            return (
                <li className='item'>
                    <div className='comment' onClick={this.commentView.bind(this,1,item.id,item.userName)}>
                        <img src={imgHead} />
                        <h5>{item.userName}</h5>
                        <p>{item.content}</p>
                    </div>
                    {
                        item.articleReply.map((reply)=>{
                            return(
                                <div className='reply'>
                                    <h5>{reply.userName}</h5>
                                    <p>{reply.content}</p>
                                </div>
                            )
                        })
                    }
                </li>
            )
        })
        let integralTags = integralList.map((item) => {
            const url = JSON.parse(item.smallImg).couponImg
            return (
                <li>
                    <img onClick={this.getPackage.bind(this,item.id)} src={url} />
                </li>
            )
        })
        return (
            <div className='pjb_infodetail'>
                <Header title={banner?data.theme:'资讯详情'} link={wherefrom=='share'||isShare||sessionStorage.userrole=='教师'||sessionStorage.userrole=='班主任'||(data.content==null&&data.displayContent==null)?null:<a className='h_link infoshare' onClick={this.share.bind(this)} />} toLink={wherefrom=='share'?'/info':null} />
                <div className="newsdetail">
                    <h5 className='title'>{data.title}</h5>
                    {data.displayContent||!data.userName?null:<p className='intro clearfix'><span className='left'>文：{data.userName==null?'':data.userName}</span><span className='left' dangerouslySetInnerHTML={{__html: data.createTime==null?'':getLocalTime(data.createTime).replace(/\./g,'-').replace(/ /g,'&nbsp;&nbsp;')}}></span><span className='right'>{data.readCount==null?'':`${data.readCount}阅`}</span></p>}
                    <div className='detail' dangerouslySetInnerHTML={{__html: decodeURIComponent(data.content==null&&data.displayContent==null?'':data.content||data.displayContent)}}>
                </div>
                {
                    wherefrom!='share'&&sessionStorage.appToken&&sessionStorage.appToken!=''&&(data.content!=null||data.displayContent!=null)&&this.props.params.sign==null?
                    <div>
                        <div className='zan'>
                            <div className={data.zan==1?'status active':'status'} onClick={this.loveInfo.bind(this)}>{data.zanCount==0?null:`${data.zanCount==null?'0':data.zanCount}人已赞`}</div>
                        </div>
                    </div>
                    :null
                }
                {integralList.length>0?
                    <ul className='mypackagelists'>
                        {integralTags}
                    </ul>:null
                }

                {wherefrom=='app'&&(data.content!=null||data.displayContent!=null)?
                    sessionStorage.userrole=='教师'||sessionStorage.userrole=='班主任'||isShare?null:
                    <div className='appsharebox'>
                        <div className='bar'>分享</div>
                        <ul className='appsharelink'>
                            <li onClick={this.shareWeixin.bind(this)}>
                                <p><img src={imgWeixin} /></p>
                                <h5>微信</h5>
                            </li>
                            <li onClick={this.shareQZone.bind(this)}>
                                <p><img src={imgPengyou} /></p>
                                <h5>朋友圈</h5>
                            </li>
                            {/*<li onClick={this.shareWeibo.bind(this)}>
                                <p><img src={imgWeb} /></p>
                                <h5>微博</h5>
                            </li>
                            <li onClick={this.shareQQ.bind(this)}>
                                <p><img src={imgQQ} /></p>
                                <h5>QQ</h5>
                            </li>
                            <li onClick={this.shareQQZone.bind(this)}>
                                <p><img src={imgQQZone} /></p>
                                <h5>QQ空间</h5>
                            </li>*/}
                        </ul>
                    </div>:null}
                    {banner?null:
                        <ul className='commentmsg'>
                            <li className='cmttopbox'>
                                <input type='text' ref='comment' autoComplete='off' placeholder='输入评论信息（最多50字）' />
                                <input className='btn' type='button' value='发布' onClick={this.commentMsg.bind(this,1)} />
                            </li>
                            {dataList.length>0?
                                <li className='cmttitle'>所有评论</li>:
                                <li className='cmttopbox'>暂无评论</li>
                            }
                            {dataLists}
                        </ul>}
                    <div  className='iosinputbox' style={{display:this.replayShow==false?'block':'none',zIndex:comment == 1?'10':'-1',opacity:comment == 1?'1':'0'}}>
                        <div className='mask replay_mask' onClick={this.commentView.bind(this, 0, '','')}/>
                        <div className='pjb_commentbox'>
                            <input type='text' ref='talk' autoComplete='off' onBlur={this.replyContentBlur.bind(this)} onFocus={this.replyContentFocus.bind(this)} id='cmtxt'/>
                            <input className='btn' type='button' value='发布' onClick={this.commentMsg.bind(this,2)} />
                        </div>
                    </div>
                    <LoadingBox dataLoad={dataLoad} dataNull={dataNull} dataEnd={dataEnd}/>
                </div>
                {sharetips?
                <div className='sharetips' onClick={this.shareTipsClose.bind(this)}>
                    <div className='mask'></div>
                    <img src={imgSharedirect} />
                </div>:null}
                <ConfirmBox config={this.config} show={show} sigle={sigle} cancel={this.cfmCancel.bind(this,0)} sure={this.cfmCancel.bind(this,1)}/>
            </div>
        )
    }
}
